<template>
  <view class="detail-container">
    <!-- 帖子内容 -->
    <view class="post-content">
      <view class="post-header">
        <image class="avatar" :src="getStaticFilePath(post.user.avatar)" mode="aspectFill"></image>
        <view class="post-info">
          <text class="username">{{ post.user.nickName }}</text>
          <text class="time">{{ post.createTime }}</text>
        </view>
      </view>
      
      <view class="post-body">
        <text class="title">{{ post.title }}</text>
        <view class="content">{{ post.content }}</view>
        <view class="image-list" v-if="processedImages && processedImages.length">
          <image 
            v-for="(img, index) in processedImages" 
            :key="index"
            :src="img"
            mode="widthFix"
            @tap="previewImage(processedImages, index)"
          ></image>
        </view>
      </view>
      
      <view class="post-footer">
        <view class="action-item" :class="{ liked: post.isLiked }" @tap="handleLike">
          <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" :color="post.isLiked ? '#FF5722' : '#666'" size="20"></uni-icons>
          <text>{{ post.likes }}</text>
        </view>
        <view class="action-item">
          <uni-icons type="chat" color="#666" size="20"></uni-icons>
          <text>{{ post.comments }}</text>
        </view>
        <view class="action-item" @tap="handleShare">
          <uni-icons type="paperplane" color="#666" size="20"></uni-icons>
          <text>分享</text>
        </view>
      </view>
    </view>
    
    <!-- 评论列表 -->
    <view class="comment-list">
      <view class="comment-title">全部评论 ({{ totalComments }})</view>
      
      <!-- 评论项循环 -->
      <view v-for="(comment, index) in commentList" 
            :key="comment.commentId" 
            class="comment-item">
        <image class="avatar" :src="getStaticFilePath(comment.user.avatar)" mode="aspectFill"></image>
        <view class="comment-content">
          <view class="comment-header">
            <text class="username">{{ comment.user.nickName }}</text>
            <text class="time">{{ comment.createTime }}</text>
          </view>
          <!-- 添加回复信息显示 -->
          <view v-if="comment.replyUser" class="reply-info">
            <text>回复</text>
            <text class="reply-target">@{{ comment.replyUser.nickName }}</text>
            <text class="reply-post" v-if="comment.replyPostTitle">「{{ comment.replyPostTitle }}」</text>
          </view>
          <view class="text">{{ comment.content }}</view>
          <view class="comment-actions">
            <view class="action-wrapper">
              <view class="action-item" :class="{ liked: comment.isLiked }" @tap="handleCommentLike(comment, index)">
              <uni-icons :type="comment.isLiked ? 'heart-filled' : 'heart'" :color="comment.isLiked ? '#FF5722' : '#666'" size="16"></uni-icons>
                <text>{{ comment.likes || 0 }}</text>
            </view>
            <view class="action-item" @tap="handleReply(comment)">
              <uni-icons type="chat" color="#666" size="16"></uni-icons>
              <text>回复</text>
              </view>
            </view>
          </view>
          
          <!-- 回复容器 -->
          <view v-if="comment.replies && comment.replies.length" class="reply-container">
            <view v-for="(reply, replyIndex) in comment.replies" 
                  :key="reply.commentId" 
                  class="reply-item">
              <view class="reply-content">
                <image class="reply-avatar" :src="getStaticFilePath(reply.user.avatar)" mode="aspectFill"></image>
                <view class="reply-body">
                  <view class="reply-header">
                    <text class="reply-username">{{ reply.user.nickName }}</text>
                    <text class="reply-to"></text>
                    <text class="target-username">{{ reply.replyUser ? reply.replyUser.nickName : comment.user.nickName }}</text>
                  </view>
                  <view class="reply-text">{{ reply.content }}</view>
                  <view class="reply-footer">
                    <text class="time">{{ reply.createTime }}</text>
                    <view class="reply-actions">
                      <view class="action-btn" :class="{ liked: reply.isLiked }" @tap="handleCommentLike(reply, index, replyIndex)">
                        <uni-icons :type="reply.isLiked ? 'heart-filled' : 'heart'" :color="reply.isLiked ? '#FF5722' : '#666'" size="14"></uni-icons>
                        <text>{{ reply.likes || 0 }}</text>
                      </view>
                      <view class="action-btn" @tap="handleReply(reply, comment)">
                        <uni-icons type="chat" color="#666" size="14"></uni-icons>
                        <text>回复</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 无评论提示 -->
      <view v-if="!commentList.length && !isCommentLoading" class="no-data">
        暂无评论
      </view>

      <!-- 加载更多评论 -->
      <view v-if="hasMoreComments" class="load-more" @tap="loadMoreComments">
        加载更多
       </view>
    </view>
    
    <!-- 评论输入框 -->
    <view class="comment-input">
      <input 
        type="text"
        v-model="commentContent"
        :placeholder="replyToName ? `回复 ${replyToName}` : '说点什么...'"
        @confirm="submitComment"
      />
      <view class="send-btn" @tap="submitComment">发送</view>
    </view>
  </view>
</template>

<script>
import { getPost, listComment, addComment, likeTarget } from '../../api/community'
import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { getStaticFilePath } from '../../utils/common'
// import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    UniIcons
  },
  data() {
    return {
      postId: '',
      post: {},
      commentList: [],
      commentContent: '',
      replyToName: '',
        replyToComment: null, // 当前回复的评论对象
        replyToParent: null, // 当前回复的父评论对象（如果是回复回复的话）
      commentPageNum: 1,
        commentPageSize: 100, // 增大页面大小以一次加载更多评论
      hasMoreComments: true,
      totalComments: 0,
        isCommentLoading: false,
        loadedCommentIds: new Set() // 用于跟踪已加载的评论ID
    }
  },
  computed: {
    processedImages() {
      if (this.post && typeof this.post.images === 'string' && this.post.images.length > 0) {
        // 添加服务器地址前缀
        return this.post.images.split(',').map(img => this.getStaticFilePath(img));
      } else if (this.post && Array.isArray(this.post.images)) {
        // 如果已经是数组，确保没有空字符串并添加服务器地址前缀
        return this.post.images.filter(img => img.length > 0).map(img => this.getStaticFilePath(img));
      }
      return [];
    }
  },
  onLoad(options) {
    console.log('detail.vue: 页面加载');
    this.postId = options.postId || '' // 从路由参数获取postId
    if (this.postId) {
      this.loadPostDetail()
      this.loadComments()
    } else {
      uni.showToast({
        title: '帖子ID缺失',
        icon: 'none'
      })
    }
  },
  onReachBottom() {
    this.loadMoreComments()
  },
  onShow() {
    console.log('detail.vue: 页面显示');
    // 检查是否需要刷新
    if (uni.getStorageSync('shouldRefreshComments_' + this.postId)) {
      console.log('detail.vue: 检测到评论刷新标记，刷新评论列表');
      this.refreshComments();
      uni.removeStorageSync('shouldRefreshComments_' + this.postId);
    }
  },
  methods: {
    getStaticFilePath, // Make the utility function available in the template
    // 加载帖子详情
    async loadPostDetail() {
      console.log('detail.vue: 加载帖子详情');
      try {
        console.log('请求帖子详情参数:', this.postId)
        const res = await getPost(this.postId)
        console.log('帖子详情响应:', res)
        if (res.code === 200) {
          this.post = {
            ...res.data,
            isLiked: res.data.isLiked || false,
            likes: res.data.likes || 0
          }
          console.log('detail.vue: post data assigned, processedImages will handle images:', this.post.images, typeof this.post.images); 
          // 确保用户信息存在
          if (!this.post.user) {
            this.post.user = { nickName: '匿名用户', avatar: '' };
          }
        } else {
          uni.showToast({
            title: res.msg || '加载帖子失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载帖子详情失败', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    // 加载评论列表
    async loadComments() {
      if (this.loading || (!this.hasMoreComments && this.commentPageNum > 1)) return;
      
      console.log('detail.vue: 加载评论列表, 页码:', this.commentPageNum);
      this.loading = true;
      
      try {
        const query = {
          pageNum: this.commentPageNum,
          pageSize: this.commentPageSize,
          postId: this.postId,
          status: '0'
        }
        console.log('请求评论列表参数:', query)
        const res = await listComment(this.postId, query)
        console.log('评论列表响应:', res)
        if (res.code === 200) {
          const rows = res.rows || [];
          
          // 更新总评论数
          this.totalComments = res.total;
          
          // 更新帖子的评论数
          if (this.post) {
            this.post.comments = res.total;
          }
          
          // 处理评论数据，添加回复信息
          const newComments = rows.map(comment => {
            // 确保用户信息存在
            if (!comment.user) {
              comment.user = { nickName: '匿名用户', avatar: '' };
            }
            // 确保回复列表存在
            if (!comment.replies) {
              comment.replies = [];
            }
            
            // 添加回复信息
            if (comment.parentId) {
              // 查找父评论
              const parentComment = rows.find(c => c.commentId === comment.parentId);
              if (parentComment) {
                comment.replyUser = parentComment.user;
                comment.replyPostTitle = this.post.title;
              }
            }
            
            // 处理回复中的回复信息
            comment.replies = comment.replies.map(reply => {
              if (!reply.user) {
                reply.user = { nickName: '匿名用户', avatar: '' };
              }
              if (reply.parentId) {
                const parentReply = comment.replies.find(r => r.commentId === reply.parentId);
                if (parentReply) {
                  reply.replyUser = parentReply.user;
                } else {
                  reply.replyUser = comment.user;
                }
                reply.replyPostTitle = this.post.title;
              }
              return reply;
            });
            
            return comment;
          });
          
          if (this.commentPageNum === 1) {
            this.commentList = newComments;
          } else {
            this.commentList = [...this.commentList, ...newComments];
          }
          
          // 更新分页信息
          this.hasMoreComments = res.total > (this.commentPageNum * this.commentPageSize);
          if (this.hasMoreComments) {
            this.commentPageNum++;
          }
          
          console.log('detail.vue: 评论加载成功, 数量:', newComments.length);
        } else {
          uni.showToast({
            title: res.msg || '加载评论失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false;
      }
    },
    
    // 上拉加载更多评论
    loadMoreComments() {
      if (!this.hasMoreComments || this.commentList.length >= this.totalComments) return
      this.commentPageNum++
      this.loadComments()
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      })
    },
    
    // 点赞帖子
    async handleLike() {
      try {
        const res = await likeTarget('1', this.post.postId) // 1代表帖子
        if (res.code === 200) {
          if (res.data === 1) { // 点赞成功
            this.$set(this.post, 'isLiked', true)
            this.$set(this.post, 'likes', this.post.likes + 1)
            uni.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 500
            })
          } else { // 取消点赞
            this.$set(this.post, 'isLiked', false)
            this.$set(this.post, 'likes', this.post.likes - 1)
            uni.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 500
            })
          }
          
          // 通知其他页面更新点赞状态
          uni.$emit('updatePostLikeStatus', {
            postId: this.post.postId,
            isLiked: this.post.isLiked,
            likes: this.post.likes
          });
          
          // 设置刷新标记
          uni.setStorageSync('shouldRefreshCommunity', true);
          uni.setStorageSync('shouldRefreshMyLikes', true);
        } else {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('点赞操作失败', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    // 点赞评论
    async handleCommentLike(comment, index) {
      try {
        const res = await likeTarget('2', comment.commentId) // 2代表评论
        if (res.code === 200) {
          if (res.data === 1) { // 点赞成功
            this.$set(this.commentList[index], 'isLiked', true)
            this.$set(this.commentList[index], 'likes', comment.likes + 1)
            uni.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 500
            })
          } else { // 取消点赞
            this.$set(this.commentList[index], 'isLiked', false)
            this.$set(this.commentList[index], 'likes', comment.likes - 1)
            uni.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 500
            })
          }
        } else {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          })
          if (res.code === 401) {
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1500);
          }
        }
      } catch (error) {
        console.error('评论点赞失败', error)
        if (error === '401') {
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    },
    
    // 处理回复
    handleReply(comment, parentComment = null) {
      this.replyToComment = comment;
      this.replyToParent = parentComment;
      this.replyToName = comment.user ? comment.user.nickName : '';
      // 聚焦到评论输入框
      this.$nextTick(() => {
        const input = this.$el.querySelector('input');
        if (input) {
          input.focus();
        }
      });
    },
    
    // 提交评论
    async submitComment() {
      if (!this.commentContent.trim()) {
        uni.showToast({
          title: '请输入评论内容',
          icon: 'none'
        });
        return;
      }
      
      try {
        console.log('detail.vue: 提交评论');
        const data = {
          postId: this.postId,
          content: this.commentContent,
          parentId: this.replyToComment ? this.replyToComment.commentId : null
        };
        
        const res = await addComment(data);
        if (res.code === 200) {
          console.log('detail.vue: 评论成功');
          // 清空评论内容和回复对象
          this.commentContent = '';
          this.replyToComment = null;
          this.replyToParent = null;
          this.replyToName = '';
          
          // 1. 刷新评论列表
          await this.refreshComments();
          
          // 2. 刷新帖子信息（更新评论数）
          await this.loadPostDetail();
          
          // 3. 通知其他页面刷新
          console.log('detail.vue: 发送刷新通知');
          uni.setStorageSync('shouldRefreshCommunity', true);
          uni.setStorageSync('shouldRefreshMyPosts', true);
          
          // 显示成功提示
          uni.showToast({
            title: '评论成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: res.msg || '评论失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('detail.vue: 评论失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    // 刷新评论列表
    async refreshComments() {
      console.log('detail.vue: 刷新评论列表');
      try {
        this.commentPageNum = 1;
        this.commentList = [];
        this.hasMoreComments = true;
        await this.loadComments();
        console.log('detail.vue: 评论列表刷新成功');
      } catch (error) {
        console.error('detail.vue: 刷新评论列表失败:', error);
      }
    },
    
    // 分享帖子
    handleShare() {
      uni.showActionSheet({
        itemList: ['复制链接', '生成分享图'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0: // 复制链接
              const shareLink = `${window.location.origin}/pages/community/detail?postId=${this.post.postId}`;
              uni.setClipboardData({
                data: shareLink,
                success: () => {
                  uni.showToast({
                    title: '链接已复制',
                    icon: 'success'
                  });
                }
              });
              break;
            case 1: // 生成分享图
              uni.showToast({
                title: '正在开发中',
                icon: 'none'
              });
              break;
          }
        }
      });
    },

    // 微信原生分享，仅在微信登录时可用
    onShareAppMessage() {
      // #ifdef MP-WEIXIN
      if (uni.getStorageSync('isWxLogin')) {
        return {
          title: this.post.title,
          path: `/pages/community/detail?postId=${this.post.postId}`,
          imageUrl: this.processedImages.length > 0 ? this.processedImages[0] : '/static/logo.png'
        }
      }
      // #endif
    },

    // 分享到朋友圈，仅在微信登录时可用
    onShareTimeline() {
      // #ifdef MP-WEIXIN
      if (uni.getStorageSync('isWxLogin')) {
        return {
          title: this.post.title,
          query: `postId=${this.post.postId}`,
          imageUrl: this.processedImages.length > 0 ? this.processedImages[0] : '/static/logo.png'
        }
      }
      // #endif
    },

    // 加载更多回复
    async loadMoreReplies(comment) {
      // 实现加载更多回复的逻辑
      // 这里可以调用后端接口获取更多回复
      // 然后将新的回复添加到 comment.replies 数组中
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.post-content {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .post-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .post-info {
      display: flex;
      flex-direction: column;

      .username {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .post-body {
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }

    .content {
      font-size: 32rpx;
      color: #555;
      line-height: 1.8;
    }

    .image-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;
      margin-top: 30rpx;

      image {
        width: 100%;
        border-radius: 12rpx;
        object-fit: cover;
      }
    }
  }

  .post-footer {
    display: flex;
    justify-content: space-around;
    padding-top: 30rpx;
    margin-top: 30rpx;
    border-top: 1rpx solid #eee;

    .action-item {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #666;
      
      &.liked {
        color: #FF5722;
      }

      text {
        margin-left: 8rpx;
      }

      .uni-icons {
        transition: color 0.3s;
      }
    }
  }
}

.comment-list {
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
}

  .comment-title {
  font-size: 32rpx;
    font-weight: bold;
  margin-bottom: 20rpx;
    color: #333;
  }

/* 主评论样式 */
  .comment-item {
    display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;

    .avatar {
    width: 80rpx;
    height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    flex-shrink: 0;
    }

    .comment-content {
      flex: 1;
    overflow: hidden;

      .comment-header {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .username {
        font-size: 28rpx;
          color: #333;
        font-weight: 500;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        margin-left: 20rpx;
        }
      }

      .reply-info {
        display: flex;
        align-items: center;
        gap: 8rpx;
        margin: 8rpx 0;
        font-size: 26rpx;
        color: #999;

        .reply-target {
          color: #007AFF;
        }

        .reply-post {
          color: #666;
          max-width: 300rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .text {
        font-size: 28rpx;
      color: #333;
      line-height: 1.5;
      margin-bottom: 10rpx;
      word-break: break-all;
      }

      .comment-actions {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 10rpx;

      .action-wrapper {
        display: flex;
        align-items: center;
        gap: 20rpx;
        flex-shrink: 0;

        .action-item {
          display: inline-flex;
          align-items: center;
          font-size: 24rpx;
          color: #666;
          cursor: pointer;
          white-space: nowrap;

          &.liked {
            color: #FF5722;
            
            .uni-icons {
              color: #FF5722;
            }
          }

          text {
            margin-left: 6rpx;
        }
        }
      }
    }
  }
}

/* 回复容器样式 */
.reply-container {
  margin: 20rpx 0 0 100rpx;
  padding: 15rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    left: -20rpx;
    top: 20rpx;
    width: 20rpx;
    height: 2rpx;
    background: #ddd;
  }
}

/* 回复项样式 */
        .reply-item {
  margin-bottom: 20rpx;
  padding: 15rpx;
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);

  &:last-child {
    margin-bottom: 0;
  }

  .reply-content {
          display: flex;
          align-items: flex-start;

    .reply-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 12rpx;
    }

    .reply-body {
      flex: 1;

      .reply-header {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: 8rpx;

        .reply-username {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }

        .reply-to {
          margin: 0 8rpx;
          color: #999;
          font-size: 24rpx;

          &::before {
            content: "回复";
            margin-right: 4rpx;
          }
        }

        .target-username {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }

      .reply-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        margin: 8rpx 0;
      }

      .reply-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 8rpx;

        .time {
          font-size: 22rpx;
          color: #999;
          }

        .reply-actions {
          display: flex;
          align-items: center;
          gap: 20rpx;

          .action-btn {
            display: flex;
            align-items: center;
            font-size: 22rpx;
            color: #666;
            cursor: pointer;

            &.liked {
              color: #FF5722;
              
              .uni-icons {
                color: #FF5722;
              }
            }

            text {
              margin-left: 4rpx;
            }
          }
        }
      }
    }
  }
}

/* 加载更多样式 */
.load-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 26rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  margin-top: 16rpx;
}

/* 评论输入框样式 */
.comment-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  input {
    flex: 1;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    margin-right: 20rpx;
    font-size: 28rpx;
  }

  .send-btn {
    width: 120rpx;
    height: 72rpx;
    line-height: 72rpx;
    text-align: center;
    background: #007AFF;
    color: #fff;
    border-radius: 36rpx;
    font-size: 28rpx;
  }
}

.no-data {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}
</style> 